<template>
  <div class="club-container">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="社团名称">
          <el-input v-model="searchForm.nameFuzzy" placeholder="请输入社团名称"></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.createTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 社团列表 -->
    <el-card class="club-list-card">
      <template #header>
        <div class="card-header">
          <h3>社团列表</h3>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col v-for="club in clubs" :key="club.id" :span="8">
          <el-card class="club-item" shadow="hover">
            <div class="club-logo">
              <el-image 
                :src="club.imageUrl || '/default-club-logo.png'"
                fit="fill"
                class="club-cover"
                :preview-src-list="club.imageUrl ? [club.imageUrl] : []"
                :preview-teleported="true"
              />
            </div>
            <div class="club-info">
              <h4 class="club-name">{{ club.name }}</h4>
              <p class="club-description">{{ club.description }}</p>
              <div class="club-stats">
                <span>成员数: {{ club.totalMemberCount || 0 }}</span>
                <el-button type="success" size="small" @click="openJoinDialog(club)">
                  参加
                </el-button>
              </div>
              <div class="club-activities" v-if="clubActivities[club.id]">
                <h5>最新活动</h5>
                <ul>
                  <li v-for="activity in clubActivities[club.id]" :key="activity.id">
                    <span class="activity-title">{{ activity.title }}</span>
                    <span class="activity-time">{{ formatDateTime(activity.startTime) }}</span>
                  </li>
                </ul>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[8, 16, 24, 32]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增：参加社团弹窗 -->
    <el-dialog
      v-model="joinDialogVisible"
      title="申请参加社团"
      width="30%"
    >
      <p>您确定要申请参加 {{ selectedClub.name }} 吗？</p>
      <!-- 新增：申请原因输入框 -->
      <el-form :model="joinForm" label-width="80px">
        <el-form-item label="申请原因">
          <el-input v-model="joinForm.applyContent" type="textarea" :rows="4" placeholder="请输入申请原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="joinDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="joinClub">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const router = useRouter()
const clubs = ref([])
const clubActivities = ref({})  // 存储每个社团的活动
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(8)

// 新增：弹窗显示控制
const joinDialogVisible = ref(false)
const selectedClub = ref(null)

// 新增：申请表单
const joinForm = reactive({
  applyContent: ''
})

// 搜索表单
const searchForm = reactive({
  nameFuzzy: '',
  createTimeRange: []
})

// 获取社团列表
const loadClubs = async () => {
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      nameFuzzy: searchForm.nameFuzzy,
      orderBy: 'created_at desc'
    }

    if (searchForm.createTimeRange && searchForm.createTimeRange.length === 2) {
      params.createdAtStart = searchForm.createTimeRange[0]
      params.createdAtEnd = searchForm.createTimeRange[1]
    }

    const res = await axios.get('/club/loadDataList', {
      params
    })

    if (res.data.status === 'success') {
      clubs.value = res.data.data.list
      total.value = res.data.data.totalCount
      // 获取每个社团的活动
      clubs.value.forEach(club => {
        loadClubActivities(club.id)
      })
    }
  } catch (error) {
    console.error('获取社团列表失败:', error)
    ElMessage.error('获取社团列表失败')
  }
}

// 获取社团活动
const loadClubActivities = async (clubId) => {
  try {
    const res = await axios.get('/activity/loadDataList', {
      params: {
        pageNo: 1,
        pageSize: 3,  // 只获取最新的3个活动
        clubId: clubId,
        orderBy: 'start_time desc'
      }
    })

    if (res.data.status === 'success') {
      clubActivities.value[clubId] = res.data.data.list
    }
  } catch (error) {
    console.error('获取社团活动失败:', error)
  }
}

// 格式化时间
const formatDateTime = (datetime) => {
  return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
}

// 查看社团活动
const viewClubActivities = (clubId) => {
  router.push(`/club/${clubId}/activities`)
}

// 打开参加社团弹窗
const openJoinDialog = (club) => {
  selectedClub.value = club
  joinForm.applyContent = '' // 清空申请原因
  joinDialogVisible.value = true
}

// 申请参加社团
const joinClub = async () => {
  try {
    const res = await axios.post('/registration/join', {
      clubId: selectedClub.value.id, // 确保 clubId 被正确传递
      applyContent: joinForm.applyContent // 确保 content 被正确传递
    }, {
      headers: {
        'Token': localStorage.getItem('token') // 添加请求头
      }
    })

    if (res.data.status === 'success') {
      ElMessage.success('申请成功')
      joinDialogVisible.value = false
    } else {
      ElMessage.error(res.data.info || '申请失败')
    }
  } catch (error) {
    console.error('申请参加社团失败:', error)
    ElMessage.error('申请失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadClubs()
}

// 重置搜索
const resetSearch = () => {
  searchForm.nameFuzzy = ''
  searchForm.createTimeRange = []
  currentPage.value = 1
  loadClubs()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  loadClubs()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  loadClubs()
}

// 初始加载
onMounted(() => {
  loadClubs()
})
</script>

<style scoped>
.club-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.club-list-card {
  min-height: 400px;
}

.club-item {
  margin-bottom: 20px;
  height: 100%;
}

.club-logo {
  width: 100%;
  height: 160px;
  overflow: hidden;
  margin-bottom: 15px;
}

.club-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.club-info {
  text-align: center;
}

.club-name {
  margin: 10px 0;
  font-size: 18px;
}

.club-description {
  color: #666;
  margin-bottom: 10px;
  /* 超出两行显示省略号 */
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.club-stats {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
  color: #666;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.club-activities {
  margin: 10px 0;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.club-activities h5 {
  margin: 0 0 10px 0;
  color: #409EFF;
}

.club-activities ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.club-activities li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 0;
  font-size: 12px;
}

.activity-title {
  color: #333;
  flex: 1;
  margin-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.activity-time {
  color: #999;
  font-size: 12px;
}

.club-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>